package com.jxb.jingchen.print;

import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.blankj.utilcode.util.ToastUtils;
import com.jxb.dialog.utils.ProgressDialogUtils;
import com.jxb.jingchen.buletooth.BluetoothReceiver;
import com.jxb.jingchen.buletooth.BluetoothUtils;
import com.jxb.jingchen.print.printer.IPrinter;
import com.jxb.jingchen.print.printer.OnPrintListener;
import com.jxb.jingchen.print.printer.OnPrintListenerImpl;
import com.jxb.jingchen.print.printer.PrinterB3SB11;

/**
 * @author jinxb
 * date     : 2021/8/16
 * desc     :
 */
public class JingChenPrintManager implements DefaultLifecycleObserver, BluetoothReceiver.OnDeviceFoundListener,
        PrinterAdapter.OnItemClickListener, OnPrintListener {
    private OnPrintListener onPrintListener;
    private BluetoothReceiver receiver;
    private PrinterDialog printerDialog;
    private IPrintTask printTask;
    private IPrinter printer;
    private Activity activity;

    public static JingChenPrintManager getInstance() {
        return PrintManagerHolder.manager;
    }

    public void print(Activity activity,IPrintTask printTask) throws Throwable {
        this.activity = activity;
        this.printTask = printTask;
        if (printer == null) {
            searchPrinter(activity);
            return;
        }
        executeTask();
    }

    private static class PrintManagerHolder {
        public static JingChenPrintManager manager = new JingChenPrintManager();
    }

    private JingChenPrintManager() {
        initReceiver();
    }

    private void initReceiver() {
        receiver = new BluetoothReceiver(this);
    }

    /**
     * 搜索打印机
     */
    private void searchPrinter(Context context) throws Throwable {
        /*
         * 步骤：
         * 第一步：判断是否支持蓝牙，不支持则return；
         * 第二步：判断是否开启蓝牙，没开启就开启
         * 第三步：搜索蓝牙设备，设备类型
         */
        if (!BluetoothUtils.bluetoothEnable()) {
            throw new Throwable("该设备不支持蓝牙功能");
        }
        if (!BluetoothUtils.isBluetoothOpened()) {
            BluetoothUtils.openBluetooth();
        }
        printerDialog = new PrinterDialog(context, this);
        printerDialog.show();
        BluetoothUtils.searchUnboundBluetoothDevice();
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        if (owner instanceof Activity) {
            ((Activity) owner).registerReceiver(receiver, receiver.getFilter());
        }
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        if (owner instanceof Activity) {
            ((Activity) owner).unregisterReceiver(receiver);
        }
    }

    /**
     * 设备发现后
     */
    @Override
    public void onDeviceFound(BluetoothDevice deviceBean) {
        //打印机的类型是1664
        boolean isPrinterType = deviceBean.getBluetoothClass().getDeviceClass() == 1664;
        if (isPrinterType) {
            printerDialog.addDevice(deviceBean);
        }
    }

    /**
     * 点击某个设备
     */
    @Override
    public void onItemClick(BluetoothDevice device) {
        /*
         * 1、先暂停搜索
         * 2\判断是否配对，如果未配对就去配对，已配对就连接
         *
         * */
        BluetoothUtils.stopSearch();
        switch (device.getBondState()) {
            case BluetoothDevice.BOND_NONE:
                if (BluetoothUtils.boundDevice(device)) {
                    connectPrinter(device);
                }
                break;
            case BluetoothDevice.BOND_BONDED:
                connectPrinter(device);
                break;
            default:
        }
    }

    private void connectPrinter(BluetoothDevice device) {
        String deviceName = device.getName();
        if (onPrintListener == null) {
            onPrintListener = new OnPrintListenerImpl();
        }
        if (deviceName.startsWith("B3S")
                || deviceName.startsWith("B11")
                || deviceName.startsWith("B50")
                || deviceName.startsWith("JC-M90")) {
            printer = new PrinterB3SB11(this);
        } else {
            return;
        }
        onConnecting();
        boolean isOpenSuccess = printer.connection(null, device);
        if (isOpenSuccess) {
            onPrintListener.onConnectSuccess();
            printerDialog.dismiss();
            onPrinting();
            executeTask();
        }else {
            onConnectFailed();
        }
    }

    private void executeTask() {
        if (printTask != null) {
            printTask.execute(printer);
        }
    }

    @Override
    public void onConnectSuccess() {
        ProgressDialogUtils.dismissProgressDialog();
        ToastUtils.showShort("打印机连接成功");
    }

    @Override
    public void onConnectFailed() {
        ProgressDialogUtils.dismissProgressDialog();
        ToastUtils.showShort("打印机连接失败");
        printer = null;
    }

    @Override
    public void onDisConnect() {
        ProgressDialogUtils.dismissProgressDialog();
        ToastUtils.showShort("打印机断开连接");
        printer = null;
    }

    @Override
    public void onPrinting() {
        ProgressDialogUtils.showProgressDialog(activity,"打印","标签打印中");
    }

    @Override
    public void onConnecting() {
        ToastUtils.showShort("打印机连接中");
        ProgressDialogUtils.showProgressDialog(activity,"打印","打印机连接中");
    }

    @Override
    public void onPrintSuccess() {
        ProgressDialogUtils.dismissProgressDialog();
        ToastUtils.showShort("标签打印成功");
    }

    @Override
    public void onPrintFailed() {
        ProgressDialogUtils.dismissProgressDialog();
        ToastUtils.showShort("标签打印失败");
    }
}
